package com.hantang.web.json.handlers;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson; 
import com.hantang.web.dao.UserDao;
import com.hantang.web.data.UserData;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.LoginRes;


public class LoginHandler extends AbstractHandler {

	private static Logger LOGGER = Logger.getLogger(LoginHandler.class);
	
	@Override
	public String doService(Request request, Response res) throws Exception {
		
		String username = request.getParameter(PARAM_USER_NAME);
		String password = request.getParameter(PARAM_PASSWORD);
		
		String str = login(username, password);
		
		LOGGER.info("logoin ....");
		
		return str;
	}

	public static String login(String username, String password) {
		LoginRes resData = new LoginRes();
		if(username != null && password != null)
		{
			int code = MetaData.META_DATA_ERROR_PARA;
			UserDao dao = new UserDao();
			UserData data = dao.loadDataByName(username);
			if(data != null)
			{
				if(data.getPassword().equals(password)){
					resData.setData(data);
					code = MetaData.META_DATA_SUCCESS_CODE;
				}else{
					code = MetaData.META_DATA_FAILED_CODE;
				}
			}
			resData.setMeta(new MetaData(code, ""));
		}
		
		Gson gson = new Gson();
		String str = gson.toJson(resData);
		return str;
	}
	
	/**
	 * 
	 * @param username
	 * @return 0 true; -1 username is not exist. -2 password is not correct.
	 * 
	 */
	public static int validate(String username,String password)
	{
		int code = -2;
		UserDao dao = new UserDao();
		UserData data = dao.loadDataByName(username);
		if(data != null)
		{
			if(data.getPassword().equals(password)){
				code = 0;
			}else{
				code = -1;
			}
		}		
		return code;
	}
	
}